package DataBases

import (
	"fmt"
	"source-admin-go/pkg/e"
	"source-admin-go/src/config"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

func init() {
	//dsn := "root:hubiao0103..@tcp(localhost:3306)/source_admin_go?charset=utf8mb4&parseTime=True&loc=Local"
	mysqlConfig := config.Server.Database.Mysql
	dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local",
		mysqlConfig.Username,
		mysqlConfig.Password,
		mysqlConfig.Url,
		mysqlConfig.Port,
		mysqlConfig.DbName)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		str := fmt.Sprintf("Error connecting to database 【%v】\n", err.Error())
		e.ErrorLogPrintln(str)
		dsnMessage := fmt.Sprintf("The DSN you use to connect to MySQL looks like this：【%v】", dsn)
		e.ErrorLogPrintln(dsnMessage)
		return
	}

	e.SuccessLogPrintln("Welcome to use MySQL, will continue to provide services for you!")
	DB = db
}
